package main.java.com.lee.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/11
 */
public class InterruptedLockTest {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                try {
                    lockDemo(lock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        t1.start();

        Thread t2 = new Thread("t2"){
            @Override
            public void run() {
                try {
                    lockDemo(lock);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread.sleep(1000);
        t2.start();
        Thread.sleep(2000);
        t2.interrupt();
        t1.join();
        t2.join();

    }

    private static void lockDemo(Lock lock) throws InterruptedException {
        if (lock.tryLock(5, TimeUnit.SECONDS)) {
            try {
                System.out.println(Thread.currentThread().getName() + ": 加锁成功");
                Thread.sleep(5000);
            }finally {
                lock.unlock();
            }
        }
    }
}
